package com.withmiku.world.user.controller;

import com.withmiku.world.user.common.Result;
import com.withmiku.world.user.service.PostLikeService;
import com.withmiku.world.user.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user/post")
public class PostLikeController {
    private final PostLikeService postLikeService;
    private final UserService userService;

    @Autowired
    public PostLikeController(PostLikeService postLikeService,
                              @Qualifier("userServiceImpl") UserService userService) {
        this.postLikeService = postLikeService;
        this.userService = userService;
    }

    /**
     * 点赞
     */
    @PostMapping("/{postId}/like")
    public Result like(@PathVariable Long postId,
                       HttpServletRequest request) {
        String username = (String)request.getAttribute("username");
        Long userId = userService.findByUsername(username).getId();

        return postLikeService.like(postId, userId)
                ? Result.success(200, "点赞成功", null)
                : Result.error("不要重复点赞");
    }

    /**
     * 取消点赞
     */
    @DeleteMapping("/{postId}/like")
    public Result unlike(@PathVariable Long postId,
                         HttpServletRequest request) {
        String username = (String)request.getAttribute("username");
        Long userId = userService.findByUsername(username).getId();

        return postLikeService.unlike(postId, userId)
                ? Result.success(200, "取消点赞成功", null)
                : Result.error("你本来就没点赞");
    }

    /**
     * 查询点赞状态
     */
    @GetMapping("/{postId}/like-status")
    public Result status(@PathVariable Long postId,
                         HttpServletRequest request) {
        String username = (String)request.getAttribute("username");
        Long userId = userService.findByUsername(username).getId();

        boolean liked = postLikeService.isLiked(postId, userId);
        long count = postLikeService.countLikes(postId);

        return Result.success(200, "查询成功", new LikeStatus(liked, count));
    }

    record LikeStatus(boolean liked, long likeCount) {
    }
}
